package handlers

import (
	"car-trade-sys/cache"
	"car-trade-sys/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Find(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	/*
		SELECT
		  car_orders.cid AS OrderId,
		  cars.car_name AS CarName,
		  cars.car_code AS CarCode,
		  cars.car_no AS CarNo,
		  car_orders.order_code AS OrderCode,
		  car_orders.order_good AS OrderGood,
		  car_orders.order_form AS OrderForm,
		  car_orders.order_to AS OrderTo
		FROM
		  car_orders
		  JOIN cars ON car_orders.cid = cars.id
	*/

	offset := (page - 1) * size
	var data []model.CarOrderList
	redis_key := "List_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_orders").
			Joins("JOIN cars ON car_orders.cid = cars.id").
			Select(
				"car_orders.cid AS OrderId",
				"cars.car_name AS CarName",
				"cars.car_code AS CarCode",
				"cars.car_no AS CarNo",
				"car_orders.order_code AS OrderCode",
				"car_orders.order_good AS OrderGood",
				"car_orders.order_form AS OrderForm",
				"car_orders.order_to AS OrderTo").
			Offset(offset).Limit(size).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	var count int64
	model.DB.Model(&model.CarOrderList{}).Count(&count)

	c.JSON(200, gin.H{
		"data":  data,
		"msg":   "查询成功",
		"code":  200,
		"count": count,
	})
}

func Detail(c *gin.Context) {
	cid := c.Query("cid")
	var data model.CarOrderList
	redis_key := "Detail_" + cid
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_orders").
			Joins("JOIN cars ON car_orders.cid = cars.id").
			Select(
				"car_orders.cid AS OrderId",
				"cars.car_name AS CarName",
				"cars.car_code AS CarCode",
				"cars.car_no AS CarNo",
				"car_orders.order_code AS OrderCode",
				"car_orders.order_good AS OrderGood",
				"car_orders.order_form AS OrderForm",
				"car_orders.order_to AS OrderTo").
			Where("car_orders.cid=?", cid).Debug().Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}

	c.JSON(200, gin.H{
		"data": data,
		"msg":  "查询成功",
		"code": 200,
	})
}
